var app = angular.module('JiangGanApp')
    app.directive('pagining', pagining);

function pagining() {
    var directive ={
        restrict: 'AE',
        templateUrl: '../templates/directives/pagining.html',
        scope:{
            pageOption:'=pageoption',
            callBack:'&callback'
        },
        transclude:true,
        replace:true,
        link: function ($scope, element, attrs) {
            //pageOption改变时推组合pages
            $scope.$watch('pageOption', function (value) {
                var pageOption = value;
                pageOption['current']=value['current']==undefined?0:value['current'];
                var pageSize = pageOption.pageSize;
                var count = pageOption.itemCount;
                pageOption['pageCount'] = Math.ceil(count/pageSize);
                var pageCount =pageOption.pageCount;
                pageOption['pages']=[]
                for(var i=0;i<pageCount;i++){
                if(i>Math.floor(count/pageSize)-1){
                    pageOption['pages'].push([i*pageSize+1,count])
                }else{
                    pageOption['pages'].push([i*pageSize+1,(1+i)*pageSize])
                }
                $scope.pageOption = pageOption;
            }
            $scope.callBack({item:$scope.pageOption.pages[$scope.pageOption.current]});
            },true);
            $scope.clickPage = function(page,$event){
                console.log(3,page)
                if(!$(event.target).parent().hasClass('disabled')){ //判定是否失效
                    $scope.pageOption.current = page;
                    $scope.callBack({item:$scope.pageOption.pages[$scope.pageOption.current]});
                }
            }
            $scope.clickPageButton = function(){
                if($("#pageInput").val()<1||$("#pageInput").val()>$scope.pageOption.pageCount){
                    alert("该页码不存在")
                    $("#pageInput").val($scope.pageOption.current+1)
                    return false;
                }else{
                    $scope.pageOption.current=$("#pageInput").val()-1;
                    $scope.callBack({item:$scope.pageOption.pages[$scope.pageOption.current]});
                }
            }
        }
    }
    return directive;
}
